<?php
/**
 * Fastlib 配置文件
 * 
 * $Id: string.php 121 2010-05-28 07:57:29Z Administrator $
 * $Revision: 121 $
 * $Author: Administrator $
 * $Date: 2010-05-28 15:57:29 +0800 (星期五, 28 五月 2010) $
 * @author glzaboy<glzaboy@163.com>
 * @package fastlib
 * @subpackage drivers
 * @copyright 2005-2010 (c) glzaboy
 */
class StringReader {
	public $_pos;
	public $_str;
	public $error;
	function __construct($str = '', $file = '') {
		if ($file != '') {
			if (file_exists ( $file )) {
				$length = filesize ( $file );
				$fp = fopen ( $file, 'rb' );
				if (! $fp) {
					$this->error = 3;
					return false;
				}
				$this->_str = fread ( $fp, $length );
				fclose ( $fp );
			} else {
				$this->error = 2; // File doesn't exist
				return false;
			}
		} else {
			$this->_str = $str;
		}
		$this->_pos = 0;
		// If string functions are overloaded, we need to use the mb versions
		$this->is_overloaded = ((ini_get ( "mbstring.func_overload" ) & 2) != 0) && function_exists ( 'mb_substr' );
		return true;
	}
	public function _substr($string, $start, $length) {
		if ($this->is_overloaded) {
			return mb_substr ( $string, $start, $length, 'ascii' );
		} else {
			return substr ( $string, $start, $length );
		}
	}
	public function _strlen($string) {
		if ($this->is_overloaded) {
			return mb_strlen ( $string, 'ascii' );
		} else {
			return strlen ( $string );
		}
	}
	public function read($bytes) {
		$data = $this->_substr ( $this->_str, $this->_pos, $bytes );
		$this->_pos += $bytes;
		if ($this->_strlen ( $this->_str ) < $this->_pos) {
			$this->_pos = $this->_strlen ( $this->_str );
		}
		return $data;
	}
	public function seekto($pos) {
		$this->_pos = $pos;
		if ($this->_strlen ( $this->_str ) < $this->_pos) {
			$this->_pos = $this->_strlen ( $this->_str );
		}
		return $this->_pos;
	}
	public function currentpos() {
		return $this->_pos;
	}
	public function length() {
		return $this->_strlen ( $this->_str );
	}
}